<template>
  <Layout>
    <Form ref="form1" :model="form1" :label-width="120">
      <Row v-show="switchFlag" class="query-form" style="padding-top: 15px">
        <Col span="8">
          <FormItem label="审计任务：">
            <Input class="query-form-el" type="text" v-model="form1.missionName"></Input>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="组长姓名：">
            <Input class="query-form-el" type="text" v-model="form1.groupLeaderName"></Input>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="审计状态：">
            <Select v-model="form1.auditState" style="width: 100%">
              <Option value="0">审计中</Option>
              <Option value="1">已审计</Option>
            </Select>
          </FormItem>
        </Col>
      </Row>
      <Row v-show="switchFlag" class="query-form" style="padding-top: 15px">
        <Col span="8" offset="16">
          <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text">收起∧</Button>
          <Button @click="reset" class="ivu-btn-reset">重置</Button>
          <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>

        </Col>
      </Row>
      <Row v-show="!switchFlag" class="query-form" style="padding-top: 15px">
        <Col span="8">
          <FormItem label="所属二级集团：" prop="order">
            <two-level-org org-code class="query-form-el" v-model="form1.twoLevelOrgId"></two-level-org>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="被审计单位：">
            <!--            <Input class="query-form-el" type="text" v-model="form1.auditedOrgId"></Input>-->
            <company-select v-model="form1.auditedOrgName" class="query-form-el"></company-select>
          </FormItem>
        </Col>
        <Col span="8">
          <!--          <Button @click="switchQuery(true)" class="ivu-btn-switch" type="text">展开∨</Button>-->
          <Button @click="reset" class="ivu-btn-reset">重置</Button>
          <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
        </Col>
      </Row>

    </Form>
    <Row class="query-form">
      <Col span="24">
        <Button type="primary" :loading="dLoading" class="ivu-btn-add" icon="md-cloud-download" @click="exportExcel">
          导出
        </Button>
        <!--<Button size="large"  class="ivu-btn-delete" icon="md-trash" @click="batDelete">删除</Button>-->
      </Col>
    </Row>

    <Table ref='table' :height="tableHeight"
           no-data-text="没有查询到相关数据！" @on-selection-change="reportSelect"
           show-summary @on-sort-change="sortChange"
           :summary-method="({columns,data})=>this.gAmountTo({columns,data},['totalCount','rectifiedCount','notRectifiedCount'])"
           :loading="buttonLoading" size="small" border :columns="columns1" :data="dataTable">
    </Table>
    <Row style="margin-right:10px;">
      <Col span="24">
        <Page :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange"
              style="float: right" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray"
              show-total show-sizer show-elevator/>
      </Col>
    </Row>

    <Modal title="审计任务信息" v-model="model2" :width=800>
      <Form :model="showdata" :label-width="160">
        <Row type="flex" justify="space-around" class="detail-background-clor">
          <Col span="11">
            <FormItem label="审计任务：" prop="stdOrgName">
              {{ showdata.missionName }}
            </FormItem>
          </Col>

          <Col span="11">
            <FormItem label="审计计划：">
              {{ showdata.auditPlanName }}
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around">
          <Col span="11">
            <FormItem label="审计基础标准：">
              {{ showdata.basicsName }}
            </FormItem>
          </Col>
          <Col span="11">
            <FormItem label="审计现场标准：">
              {{ showdata.sceneName }}
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="detail-background-clor">
          <Col span="11">
            <FormItem label="审计班组标准：">
              {{ showdata.teamName }}
            </FormItem>
          </Col>
          <Col span="11">
            <FormItem label="被审计单位：" prop="stdOrgName">
              {{ showdata.auditedOrgName }}
            </FormItem>
          </Col>
        </Row>


        <Row type="flex" justify="space-around">
          <Col span="11">
            <FormItem label="开始时间：">
              {{ formatDate(new Date(showdata.planStart), 'yyyy-MM-dd') }}
            </FormItem>
          </Col>
          <Col span="11">
            <FormItem label="结束时间：">
              {{ formatDate(new Date(showdata.planEnd), 'yyyy-MM-dd') }}
            </FormItem>
          </Col>

        </Row>
        <Row type="flex" justify="space-around" class="detail-background-clor"
             v-if="showdata.safetyPersionName && showdata.twoSafetyPersionName">
          <Col span="11">
            <FormItem label="集团安全审计负责人：">
              {{ showdata.safetyPersionName }}
            </FormItem>
          </Col>
          <Col span="11">
            <FormItem label="二级集团安全审计负责人：">
              {{ showdata.twoSafetyPersionName }}
            </FormItem>
          </Col>
        </Row>


      </Form>
      <div slot="footer">
        <Button class='ivu-btn-save' @click="onCancel">关闭</Button>
      </div>
    </Modal>

    <Modal title="整改后上报" v-model="model10" :width=800>
      <Form ref="showdata" :model="obj" :label-width="160" :rules="ruleCustom">
        <Row type="flex" justify="space-around">
          <Col span="23">
            <FormItem label="二级集团安全审计负责人：" prop="user1">
              <Select v-model="obj.user1">
                <Option v-for="item in secondaryGroupPersionList" :value="item.userId" :key="item.userId">
                  {{ item.userName }}
                </Option>
              </Select>
            </FormItem>
          </Col>
        </Row>
      </Form>
      <div slot="footer">
        <Button class='ivu-btn-save' :loading="loading2" @click="submit('showdata')">确定</Button>
        <Button class='ivu-btn-cancel' @click="handleCancel">取消</Button>
      </div>
    </Modal>

    <Modal :transfer=false v-model="model4" :width=900>
      <Tabs>
        <TabPane label="历史记录">
          <Table ref='table1' border :columns="columns2" no-data-text="没有查询到相关数据！" style="margin-top: 0"
                 :loading="loading3"
                 :data="history" width="100%" :height="450" highlight-row stripe size="small"></Table>
        </TabPane>
        <TabPane label="流程图">
          <div style="height: 450px; overflow-y: auto; overflow-x: auto">
            <img :src="imgUrl">
          </div>
        </TabPane>
      </Tabs>
      <div slot="footer">
        <Button @click="model4=false" class="ivu-btn-save">关闭</Button>
      </div>
    </Modal>
    <Modal title='指派下级企业整改' :transfer=false v-model="adtAssignModel" :width=800>

      <div style="height:300px;overflow-y:auto">

        <Form ref="adtAssign" :model="adtAssign" :rules="adtAssignRuleCustom" label-position="top">

          <Row type="flex" justify="space-around" class="code-row-bg" style="margin-top: 20px">
            <Col span="23">
              <FormItem label="已选择企业：" prop="orgIds">
                <div class='tag-input'>
                  <Tag v-for='(tag, index) in adtAssign.orgIds' :key='tag.orgId'
                       type="border" closable @on-close="removeNote(index)">{{ tag.orgName }}
                  </Tag>
                  <Button icon="ios-plus-empty" type="dashed" size="small" @click="addCompany">新增</Button>
                </div>
              </FormItem>
            </Col>
          </Row>

        </Form>
      </div>
      <div slot="footer">
        <Button class='ivu-btn-save' :loading="loading" @click="adtAssignSave('adtAssign')">确定</Button>
        <Button class='ivu-btn-cancel' @click="adtAssignCancel">取消</Button>
      </div>
      <Spin size="large" v-if="assignLoading"></Spin>
    </Modal>
    <cascaderMultiple ref="cascaderDom" @setData="setNotes" :rootOrgId="crrentUser.companyId">

    </cascaderMultiple>
  </Layout>
</template>

<script>
import {Api} from '@/api/index.js'
import _deepclone from 'lodash/cloneDeep'
import {sessionStorage} from '@/common/cacheUtils.js';
import cascaderDom from '../../../components/cascader-dom.vue';
import cascaderMultiple from '@/components/cascader-dom-multiple.vue'

export default {
  components: {
    cascaderDom, cascaderMultiple
  },
  data() {
    return {
      model10: false,
      adtAssignModel: false,
      loading: false,
      groupPersionList: [],
      adtAssign: {},
      secondaryGroupPersionList: [],
      user: sessionStorage('userId').getObject('userId'),
      obj: {},
      buttonLoading2: false,
      addLoading: false,
      crrentUser: sessionStorage('userId').getObject('userId'),
      curPlan: {},
      teams: [],
      expertSelectModal: false,
      upLoadList: [],
      imgUrl: "",
      assignLoading: false,
      selectUsers: [],
      appStatusList: [],
      currentUser: JSON.parse(sessionStorage('userId').get('userId')),
      locationList: [],
      stdRankList: [],
      supervisors: [],
      downloadUrl: Api.downloadMongoFile,
      upUrl: Api.uploadMongoFile,
      switchFlag: false,
      form1: {},
      pageSizeArray: [10, 20, 50],
      dLoading: false,
      pagedata: {
        total: 0,
        pageSize: 10,
        currentPage: 1,
      },
      dataTable: [],
      adtAssignRuleCustom: {
        orgIds: [{
          validator: (rule, value, callback) => {
            if (!value) {
              callback(" ")
              this.$Message.error("请添加审计单位！");
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
      },
      columns2: [
        {type: 'index', title: '序号', width: 80, align: 'center',},
        {width: 180, title: '审批时间', key: 'endTime', align: 'center',},
        {width: 185, title: '节点名称', key: 'name', align: 'center',},
        {width: 120, title: '审批人', key: 'userName', align: 'center'},
        {width: 100, title: '审批意见', key: 'route', align: 'center'},
        {width: 200, title: '备注', key: 'opinions', align: 'center'},
      ],
      columns1: [
        {
          title: "序号",
          width: 80,
          align: "center",
          fixed: 'left',
          render: (h, params) => {
            if (params.row.missionId === "-1") return h('span', "汇总");
            return h('span', (params.index) - 1 + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
          }
        },
        {
          title: '状态',
          align: 'center',
          key: 'status',
          fixed: 'left',
          width: 100,
          render: (h, params) => {
            let color = 'green';
            if (params.row.procinstState == undefined || params.row.procinstState == null || params.row.procinstState == 2 || params.row.procinstState == 5) {
              color = 'red';
            }
            if (params.row.procinstState == 1) {
              color = 'blue';
            }
            return h('div', [
              h('span', {
                style: {
                  color: color
                }
              }, params.row.missionId == '-1' ? '' : params.row.procinstState == 1 ? '审批中' : params.row.procinstState == 2 ? '被退回' : params.row.procinstState == 3 ? '审批通过' : '未上报' || '--')
            ]);
          }
        },

        {
          title: '总问题数量',
          align: 'center',
          key: 'totalCount',
          fixed: 'left',
          width: 100,
          render: (h, params) => {
            return h('div', [
              h('span', {
                style: {
                  color: 'blue'
                }
              }, params.row.totalCount),
            ]);
          }
        },
        {
          title: '已整改问题数量',
          align: 'center',
          key: 'rectifiedCount',
          fixed: 'left',
          width: 100,
          render: (h, params) => {
            return h('div', [
              h('span', {
                style: {
                  color: 'green'
                }
              }, params.row.rectifiedCount),
            ]);
          }
        },
        {
          title: '未整改问题数量',
          align: 'center',
          key: 'notRectifiedCount',
          fixed: 'left',
          width: 100,
          render: (h, params) => {
            return h('div', [
              h('span', {
                style: {
                  color: 'red'
                }
              }, params.row.notRectifiedCount),
            ]);
          }
        },
        {
          title: '被审计单位',
          minWidth: 280,
          align: 'center',
          key: 'auditedOrgName',
          fixed: 'left',
        },
        {
          title: '开始时间',
          minWidth: 120,
          align: 'center',
          sortable: "custom",
          key: 'planStart',
          render: (h, params) => {
            return h('div', [
              (params.row['planStart'] ? this.formatDate(new Date(params.row.planStart), 'yyyy-MM-dd') : '')
            ]);
          }
        },
        {
          title: '结束时间',
          minWidth: 120,
          align: 'center',
          sortable: "custom",
          key: 'planEnd',
          render: (h, params) => {
            return h('div', [
              (params.row['planEnd'] ? this.formatDate(new Date(params.row.planEnd), 'yyyy-MM-dd') : '')
            ]);
          }
        },

        {
          title: '操作',
          key: 'action',
          fixed: 'right',
          width: 240,
          align: 'center',
          render: (h, params) => {
            if (params.row.missionId == '-1') {
              return;
            }
            if (params.row.rectifiedCount == params.row.totalCount && (params.row.procinstState == null || params.row.procinstState == '5')) {
              return h('div', [
                h('A', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    fontSize: '14px'
                  },
                  on: {
                    click: () => {
                      this.getAdtAssign(params.row);
                    }
                  }
                }, '指派整改'),
                h('Divider', {
                  props: {
                    type: 'vertical',
                  }
                }, ''),
                h('A', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    fontSize: '14px'
                  },
                  on: {
                    click: () => {
                      this.$router.push({path: '/problemRectItem', query: params.row});
                    }
                  }
                }, '问题清单'),
                h('Divider', {
                  props: {
                    type: 'vertical',
                  }
                }, ''),
                h('a', {
                  props: {
                    type: 'primary',
                  },
                  style: {
                    fontSize: '14px',
                    color: params.row.procinstId == null ? '#d0d0d0' : '',
                    pointerEvents: params.row.procinstId == null ? 'none' : ''
                  },
                  on: {
                    click: () => {
                      this.imgUrl = Api.getFlowImg + '/' + params.row.procinstId
                      this.showHistory(params.row);
                    }
                  }
                }, '审批记录'),
                h('A', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    fontSize: '14px'
                  },
                  on: {
                    click: () => {
                      this.showData(params, 1);
                    }
                  }
                }, '详情'),
                h('Divider', {
                  props: {
                    type: 'vertical',
                  }
                }, ''),
                h('A', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    fontSize: '14px'
                  },
                  on: {
                    click: () => {
                      this.obj = {};
                      this.obj.workId = params.row.missionId;
                      this.obj.createUserId = this.user.userId;
                      this.obj.userName = this.user.userName;
                      this.obj.key = "problemRect";
                      this.obj.formKey = "problemRectForApproval";
                      this.model10 = true;
                    }
                  }
                }, '上报'),
              ]);
            } else {
              return h('div', [
                h('A', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    fontSize: '14px'
                  },
                  on: {
                    click: () => {

                      // this.adtAssign.missionId = params.row.missionId;
                      this.getAdtAssign(params.row);
                    }
                  }
                }, '指派整改'),
                h('Divider', {
                  props: {
                    type: 'vertical',
                  }
                }, ''),
                h('A', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    fontSize: '14px'
                  },
                  on: {
                    click: () => {
                      this.$router.push({path: '/problemRectItem', query: params.row});
                    }
                  }
                }, '问题清单'),
                h('Divider', {
                  props: {
                    type: 'vertical',
                  }
                }, ''),
                h('a', {
                  props: {
                    type: 'primary',
                  },
                  style: {
                    fontSize: '14px',
                    color: params.row.procinstId == null ? '#d0d0d0' : '',
                    pointerEvents: params.row.procinstId == null ? 'none' : ''
                  },
                  on: {
                    click: () => {
                      this.imgUrl = Api.getFlowImg + '/' + params.row.procinstId
                      this.showHistory(params.row);
                    }
                  }
                }, '审批记录'),
                h('A', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    fontSize: '14px'
                  },
                  on: {
                    click: () => {
                      this.showData(params, 1);
                    }
                  }
                }, '详情'),
                h('Divider', {
                  props: {
                    type: 'vertical',
                  }
                }, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px', color: '#c5c8ce', pointerEvents: 'none'},
                }, '上报'),
              ]);
            }
          }
        },
      ],
      ruleCustom: {
        user1: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else if (value < 0) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        user2: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else if (value < 0) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
      },
      auditedOrgName: '',
      auditedOrgId: '',
      basics: [],
      basicsMap: {},
      reportSelectAll: [],
      scene: [],
      sceneMap: {},
      add: false,
      model1: false,
      model2: false,
      model3: false,
      showdata: {},
      location: null,
      form1datacopy: {},
      files: [],
      buttonLoading: false, tableHeight: 10,
      ruleCustom2: {
        title: [
          {
            required: true,
            message: '  ',
            trigger: 'change, blur'
          }
        ],
        content: [
          {
            required: true,
            message: '  ',
            trigger: 'change, blur'
          }
        ],
        closingDate: [
          {
            required: true,
            type: 'date',
            message: '  ',
            trigger: 'change, blur'
          }
        ]
      },
      formData: {},
      column3: [
        {
          type: 'index',
          title: '序号',
          width: 80,
          align: 'center',
          fixed: 'left',
        },
        {
          title: '企业名称',
          align: 'center',
          key: 'companyName',
          minWidth: 200,
          render: (h, params) => {
            return h('div', [
              h('span', params.row.companyName || '--')
            ]);
          }
        },
        {
          title: '企业邮箱',
          align: 'center',
          key: 'officeMail',
          minWidth: 200,
          render: (h, params) => {
            return h('div', [
              h('span', params.row.officeMail || '--')
            ]);
          }
        },
        {
          title: '附件类型',
          align: 'center',
          key: 'twoCompanyName',
          minWidth: 200,
          render: (h, params) => {
            return h('div', [
              h('span', params.row.twoCompanyName || '--')
            ]);
          }
        },
      ],
      infos3: [],
      loading2: false,
      model4: false,
      loading3: false,
      history: [],
    }
  },
  mounted() {
    this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145 - 40;
    this.selectCodingSort();
    this.query();
  },
  methods: {
    rectLeaderChange(appStatus) {
      if (appStatus) {
        this.form1datacopy.supervisorId = appStatus.value;
        this.form1datacopy.supervisor = appStatus.label;
      }
    },
    sortChange(data) {
      if (data.order === 'asc' || data.order === 'desc') {
        let order = data.key
        this.form1.dynamicSort = order + ' ' + data.order
        this.query()
      }
    },
    adtAssignSave(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.loading = true;
          this.$http.post(Api.adtAssignAdd, this.adtAssign).then((res) => {
            this.loading = false;
            if (res.data.status === 200) {
              this.$Message.success('成功');
              this.adtAssignModel = false;
              this.query()

            } else if (res.data.status === 201) {
              this.$Message.error(res.data.msg);
            }

          }).catch(e => {
            this.loading = false;
            this.adtAssignModel = false;
            this.query();
            this.$Message.error("数据获取失败")
          })
        } else {
          this.$Message.error('请选择企业!');
        }
      })
    },
    addCompany() {
      this.$refs.cascaderDom.openOrgModal(_deepclone(this.adtAssign.orgIds));
    },
    removeNote(index) {
      this.adtAssign.orgIds.splice(index, 1)
      this.$forceUpdate();
    },
    getAdtAssign(data) {
      this.adtAssign = {
        orgIds: [],
        missionId: data.missionId,
      };
      this.adtAssignModel = true;
      this.assignLoading = true;
      let _this = this;
      this.$http.get(Api.adtAssignList + '/' + data.missionId).then((res) => {
        if (res.data.status === 200) {
          res.data.data.forEach(item => {
            _this.adtAssign.orgIds.push({orgId: item.orgId, orgName: item.orgName});
          });
        } else {
          this.$Message.error(res.data.msg)
        }
        this.assignLoading = false;

      }).catch(e => {
        this.$Message.error("数据获取失败")
      })
    },
    adtAssignCancel() {
      this.adtAssign = {};
      this.adtAssignModel = false;
    },
    setQueryOrgId(data) {
      this.form1.auditedOrgId = data[data.length - 1];
    },
    exportExcel() {
      let orgId = sessionStorage('userId').getObject('userId').companyId;
      let userId = sessionStorage('userId').getObject('userId').userId;
      let data = {
        createOrgId: orgId,
        createUserId: userId
      };
      data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));
      data.groupLeaderName = this.form1.groupLeaderName || ''
      this.dLoading = true;
      this.$http.get(Api.downloadProblemRectList, {
        params: data,
        responseType: 'arraybuffer'
      }).then((res) => {
        this.dLoading = false;
        this.ifSpin = false;
        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: "application/vnd.ms-excel"
        })
        aLink.href = URL.createObjectURL(blob);
        aLink.download = "审计清单.xlsx" //标题
        aLink.click();
        document.body.appendChild(aLink);
      })
    },
    auditTypesChange(stdRank) {
      if (stdRank) {
        this.form1datacopy.auditTypeId = stdRank.value;
        this.form1datacopy.auditTypeName = stdRank.label;
      }
    },
    showHistory(row) {
      this.model4 = true;
      this.loading3 = true;
      this.$http.get(Api.getHistory + '/' + row.procinstId, {params: {}}).then((res) => {
        this.history = res.data;
        this.loading3 = false;
      }).catch(e => {
        this.$Message.error("数据获取失败")
      })
    },

    setNotes(data) {
      this.$set(this.adtAssign, 'orgIds', data)
      this.$forceUpdate();
    },
    openExpertSelector(isLeader) {
      this.$refs.selExpert.isLeader = isLeader
      this.$refs.selExpert.form2 = {
        members: this.form1datacopy.membersName ? this.form1datacopy.membersName : '',
        membersId: '',
        membersUserId: ''
      };
      this.selectUsers = []
      let hasVal = this.form1datacopy.membersId && this.form1datacopy.membersId.length > 1
      let mId = hasVal ? this.form1datacopy.membersId.split(',') : []
      let mName = hasVal ? this.form1datacopy.membersName.split(',') : []
      let mUId = hasVal ? this.form1datacopy.membersUserId.split(',') : []
      let i = 0
      mId.forEach(v => {
        let userInfo = {name: mName[i], expertId: v, userId: mUId[i]}
        i++
        this.selectUsers.push(userInfo)
      })

      this.expertSelectModal = true;
    },
    onCancel() {
      this.model2 = false
    },
    closeModal1() {
      this.expertSelectModal = false;
      this.selectUsers = []
    },
    getActivityData(row) {
      console.log('getActivityData(row)', row)
      if (this.$refs.selExpert.isLeader == 1) {
        this.form1datacopy.groupLeaderId = row.expertId;
        this.form1datacopy.groupLeaderName = row.userName;
        this.form1datacopy.groupLeaderUserId = row.userId;
        this.expertSelectModal = false;
      } else {
        this.form1datacopy.membersId = row.membersId.join(',')
        this.form1datacopy.membersName = row.members.join(',')
        this.form1datacopy.membersUserId = row.membersUserId.join(',')
      }
    },

    selectLocation(location) {
      this.form1datacopy.locationId = location.value;
      this.form1datacopy.location = location.label;
    },
    selectstdRank(stdRank) {
      this.form1datacopy.stdRankId = stdRank.value;
      this.form1datacopy.stdRank = stdRank.label;
    },
    selectAppStatus(appStatus) {
      this.form1datacopy.appStatusId = appStatus.value;
      this.form1datacopy.appStatus = appStatus.label;
    },
    reportSelect(select) {
      this.reportSelectAll = [];
      select.forEach(item => {
        this.reportSelectAll.push(item.missionId)
      });
      console.log(this.reportSelectAll)
    },
    beforeUploadOther(file) {
      this.files.push(file);

      return false;
    },
    submitReportSelect() {
      let _this = this;
      if (_this.reportSelectAll.length !== 0) {
        let config = {
          title: '系统提示',
          content: '完成审计后问题不可修改是否确定完成审计?',
          okText: '确定',
          cancelText: '取消',
          onOk: function () {
            let data = {
              userId: sessionStorage('userId').getObject('userId').userId,
              list: _this.reportSelectAll,
            }
            this.$http.post(Api.submitSelectAdtMission, data).then((res) => {
              if (res.data.status == '200') {
                _this.$Message.success("确认成功");
                _this.query();
              } else {
                _this.$Message.warning(res.data.msg);
                _this.query();
              }

            }).catch(e => {
              this.query();
              this.$Message.error("失败")
            })

          }

        }
        this.$Modal.confirm(config);
      } else {
        _this.$Message.warning("请先勾选审计任务")
      }

    },
    deleteFile(index) {
      this.files.splice(index, 1);
    },
    setOrgId(data) {
      this.form1datacopy.auditedOrgId = data[data.length - 1];
    },
    setOrgName(data) {
      this.form1datacopy.auditedOrgName = data;
    },
    deleteData(params) {
      this.$Modal.confirm({
        title: '数据删除',
        content: '<p>确定删除该条信息</p>',
        okText: '确认',
        onOk: () => {
          let url = Api.deleteAdtMission;
          this.$http.get(url, {params: {id: params.row.missionId}}).then((res) => {
            if (res.status === 200) {
              this.$Message.success('成功');
              this.query()
            } else if (res.data.status === 201) {
              this.$Message.error(res.data.msg);

            }
          }).catch(e => {
            this.$Message.error('请求失败' + e);
          })
        },
        cancelText: '取消'
      });
    },


    getSelectRows(rows) {
      this.deleteRows = rows;
    },
    batDelete() {

    },
    addInfo() {
      let userName = JSON.parse(sessionStorage('paramUserInfo').get('userInfo'))["createUserName"]
      this.form1datacopy = {
        createDate: this.formatDate(new Date(), 'yyyy-MM-dd'),
        createUserName: userName,
        auditPlanName: this.curPlan.auditPlanName,
        auditPlanId: this.curPlan.auditPlanId,
        planStartTime: this.curPlan.planStartTime,
        planEndTime: this.curPlan.planEndTime
      };
      this.auditedOrgName = '';
      this.auditedOrgId = '';
      this.model1 = true;
      this.add = true;
    },
    pageChange(pageNum) {
      this.pagedata.currentPage = pageNum;
      this.query();
    },
    pageSizeChange(pageSize) {
      this.pagedata.pageSize = pageSize;
      this.query();
    },
    handleCancel() {
      this.showdata = {};
      this.model1 = false;
      this.model10 = false;
    },
    forMap(arr) {
      let map = {};
      arr.forEach(item => {
        map[item["id"]] = item["standardsName"]
      })
      return map;
    },
    selectCodingSort() {
      //二级集团
      this.$http.get(Api.queryRoleUser + "/" + "843197356dd443d099542d7ebe22b2be", {
        params: {
          orgId: sessionStorage('userId').getObject('userId').twoLevelOrgId,
          two: true
        }
      }).then((res) => {
        this.secondaryGroupPersionList = res.data.data;
      }).catch(e => {
        this.$Message.error("数据获取失败")
      });
      //集团
      this.$http.get(Api.queryRoleUser + "/" + "17744170d3c24383bd283fbe72f3d664").then((res) => {
        this.groupPersionList = res.data.data;
      }).catch(e => {
        this.$Message.error("数据获取失败")
      });

    },
    switchQuery(flag) {
      this.switchFlag = flag;
      if (!this.switchFlag) {
        this.tableHeight = window.innerHeight - 220;
      } else {
        this.tableHeight = window.innerHeight - 315;
      }
    },
    reset() {
      this.form1 = {};

      this.query();


    },
    query() {
      this.buttonLoading = true;
      let orgId = sessionStorage('userId').getObject('userId').companyId;
      let userId = sessionStorage('userId').getObject('userId').userId;
      let data = {
        currentPage: this.pagedata.currentPage,
        size: this.pagedata.pageSize,
        createOrgId: orgId,
        createUserId: userId
      };
      data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));
      data.groupLeaderName = this.form1.groupLeaderName || ''
      let url = Api.queryProblemRectList;
      this.$http.get(url, {params: data}).then((res) => {
        this.dataTable = res.data.data;
        if (this.dataTable) {
          this.dataTable.unshift(res.data.totalData)
        }
        this.pagedata.total = res.data.totalSize;
        this.buttonLoading = false

      }).catch(e => {
        this.$Message.error("数据获取失败")
      })
    },
    showData(data, flag) {
      this.auditedOrgId = data.row.auditedOrgId;
      this.auditedOrgName = data.row.auditedOrgName;
      data.row.createDate = this.formatDate(new Date(data.row.createDate), 'yyyy-MM-dd')
      if (flag == 1) {
        //查看页面
        this.showdata = data.row;
        this.model2 = true;
      } else {
        //修改页面
        this.add = false;
        this.form1datacopy = JSON.parse(JSON.stringify(data.row));
        console.log('this.form1datacopy=', this.form1datacopy)

        this.model1 = true;
      }
    },
    formatDate(date, fmt) {
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
      };
      for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
          let str = o[k] + '';
          fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
        }
      }
      return fmt;
    },

    submit(name) {
      let _this = this;
      this.$refs[name].validate((valid) => {
        if (valid) {
          let url = Api.updateProblem;
          _this.loading2 = true;
          this.$http.get(url + _this.obj.workId).then(function (res) {
            this.$http.post(Api.submit, _this.obj).then(function (res) {
              _this.loading2 = false;
              _this.$Message.success({
                content: '上报成功',
                duration: 4
              });
              _this.model10 = false
              this.query();
            }, function (err) {
              _this.loading2 = false;
              _this.$Message.error({
                content: '上报失败',
                duration: 4
              });
            });
          }, function (err) {
            _this.loading2 = false;
            _this.$Message.error({
              content: '上报失败',
              duration: 4
            });
          });


        } else {
          this.$Message.error('请填报完整!');
        }
      })
    },
    padLeftZero(str) {
      return ('00' + str).substr(str.length);
    },
    openMail(row) {
      let userId = row.groupLeaderId + ',' + row.membersUserId;
      let orgId = row.auditedOrgId;
      this.$set(this.formData, 'workId', row.missionId);
      this.$set(this.formData, 'inspectionUnit', row.auditedOrgName);
      this.$set(this.formData, 'groupLeaderName', row.groupLeaderName);
      this.$set(this.formData, 'groupLeaderId', row.groupLeaderUserId);
      this.$set(this.formData, 'groupMeetsId', row.membersUserId);
      this.$set(this.formData, 'startDate', row.planStart);
      this.$set(this.formData, 'endDate', row.planEnd);

      this.$http.get(Api.queryMail, {
        params: {orgId: orgId, userId: userId}
      }).then(function (res) {
        if (res.data.status == 200) {
          if (res.data.data.length == 0) {
            this.$Notice.warning({
              title: '未找到相关机构邮箱！',
              desc: '请检查邮箱管理！'
            });
          } else {
            this.infos3 = res.data.data;
          }
        } else {
          this.$Message.error('查询失败');
        }
      }, function (res) {
        this.$Message.error('请求失败');
        this.loading = false;
      });
      this.model3 = true;
    },
    sendMail() {
      this.$refs['ruleCustom2'].validate((valid) => {
        if (valid) {
          this.formData.configList = this.infos3;
          this.buttonLoading2 = true;
          this.$http.post(Api.sendMail, this.formData).then(function (response) {
            this.buttonLoading2 = false;
            if (response.data.status == 200) {
              this.model3 = false;
              this.$Message.success({content: '发送成功', duration: 4});
            } else {
              this.$Message.error({content: '发送失败，请联系管理员！', duration: 4});
            }
          });
        }
      });
    }
  },
  watch: {
    "model1": function (qw, er) {
      if (qw && this.model1) {
        setTimeout(() => {
          this.$refs.trainOrg.setCurrentOrg();

        }, 100)
      } else {
        this.$refs.trainOrg.setCurrentOrg();

      }
    },

    "expertSelectModal": function (qw, er) {
      if (qw && this.model1) {
        setTimeout(() => {
          //this.$refs.trainOrg.setCurrentOrg();

        }, 100)
      } else {
        this.$refs.selExpert.reset();

      }
    },
    "model3": function (qw, er) {
      if (!qw) {
        this.formData = {};
        this.infos3 = [];
      }
    },
  },


}
</script>

<style lang='css' scoped>
@import '../../../index.css';

.tag-input {
  width: 100%;
  border: 1px solid #eee;
  font-size: 0.9em;
  height: 200px;
  box-sizing: border-box;
  padding: 0 10px;
  overflow-y: auto;
}
</style>
